package com.xiaobaibai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobaibai.dao.DistributionPayDao;
import com.xiaobaibai.entity.DistributionPay;
import com.xiaobaibai.entity.DistributionRecording;
import com.xiaobaibai.entity.DistributionUser;
import com.xiaobaibai.service.IDistributionPayService;
import com.xiaobaibai.service.IDistributionRecordingService;
import com.xiaobaibai.service.IDistributionUserService;
import com.xiaobaibai.units.pay.BigDecimalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaobaibai
 * @since 2020-11-23
 */
@Service
public class DistributionPayServiceImpl extends ServiceImpl<DistributionPayDao, DistributionPay> implements IDistributionPayService {

    @Autowired
    private IDistributionUserService distributionUserService;

    @Autowired
    private IDistributionRecordingService distributionRecordingService;

    @Override
    @Transactional
    public void applicationPay(Integer userId, BigDecimal amount,Integer distributionId) {
        //减去金额
        QueryWrapper<DistributionUser> q1=new QueryWrapper<>();
        q1.select("id","amount");
        q1.eq("user_id",userId);
        DistributionUser distributionUser = distributionUserService.getOne(q1);
        distributionUser.setAmount(//减少金额
                BigDecimalUtil.sub(distributionUser.getAmount().doubleValue(),amount.doubleValue()));
        distributionUserService.updateById(distributionUser);
        //申请提现
        DistributionPay distributionPay=new DistributionPay();
        distributionPay.setUserId(userId);
        distributionPay.setAmount(amount);
        distributionPay.setStatus(false);//待处理
        this.save(distributionPay);
        //增加记录
        DistributionRecording distributionRecording=new DistributionRecording();
        distributionRecording.setDistributionId(distributionId);
        distributionRecording.setAmount(amount.negate());//存入负数
        distributionRecording.setOrderId(null);
        distributionRecordingService.save(distributionRecording);
    }

}
